//
//  CYCommentReplyListViewController.m
//  cyydt
//
//  Created by chu on 2019/2/13.
//  Copyright © 2019 chu. All rights reserved.
//

#import "CYCommentReplyListViewController.h"
#import "CYCommentReplyListTableViewCell.h"

@interface CYCommentReplyListViewController ()<UITableViewDelegate, UITableViewDataSource, HPGrowingTextViewDelegate>
{
    CGFloat _inputViewHeight;
    UIButton *_zanBtn;
}
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataSourceArr;

@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIView *inputView;
@property (nonatomic, strong) HPGrowingTextView *growingTextView;

@end

@implementation CYCommentReplyListViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    IQKeyboardManager *keyboardManager =  [IQKeyboardManager sharedManager];
    keyboardManager.enable = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    IQKeyboardManager *keyboardManager =  [IQKeyboardManager sharedManager];
    keyboardManager.enable = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"回复详情";
    _inputViewHeight = 50;
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.bottomView];
    [self.view addSubview:self.inputView];
    [self.inputView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).with.mas_equalTo(50);
        make.left.equalTo(self.view).with.mas_offset(0);
        make.right.equalTo(self.view).with.mas_offset(0);
        make.height.mas_equalTo(50);
    }];
    [self getData];
    
    self.tableView.estimatedRowHeight = 44;
    if (@available(iOS 11.0, *)) {
        self.tableView.estimatedSectionFooterHeight = 0;
        self.tableView.estimatedSectionHeaderHeight = 0;
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self initZanData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSourceArr.count + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CYCommentReplyListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CYCommentReplyListTableViewCell"];
    if (!cell) {
        cell = [[NSBundle mainBundle] loadNibNamed:@"CYCommentReplyListTableViewCell" owner:nil options:nil][0];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.row == 0) {
        cell.commentModel = self.commentModel;
        cell.timeLabel.text = [NSString stringWithFormat:@"%@    %@人赞了你",self.commentModel.createTime, self.commentModel.likeNumber];
    }else{
        cell.commentModel = self.dataSourceArr[indexPath.row - 1];
    }
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewAutomaticDimension;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0001f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    return view;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0001f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

#pragma mark - 获取回复列表
- (void)getData{
    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"replies"];
    NSDictionary *param = @{@"commentId":self.commentModel.ID, @"page":@"1"};
    [[XBRequest sharedInstance] getDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"获取回复列表 ---- %@",responseResult);
        if ([self.tableView.mj_header isRefreshing]) {
            [self.tableView.mj_header endRefreshing];
        }
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                if ([responseResult[@"data"] isKindOfClass:[NSArray class]]) {
                    NSArray *data = responseResult[@"data"];
                    [self.dataSourceArr removeAllObjects];
                    for (NSDictionary *dic in data) {
                        CYCommentModel *model = [CYCommentModel modelWithDictionary:dic];
                        [self.dataSourceArr addObject:model];
                    }
                    [self.tableView reloadData];
                }
            }else{
                
            }
        }
    }];
}

#pragma mark - 发布回复
- (void)fasongHuiFuWithText:(NSString *)content{
    [EasyShowLodingView showLoding];
    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"inserReply"];
    NSDictionary *param = @{@"toUserId":self.commentModel.userId, @"type":self.commentModel.type, @"commentId":self.commentModel.ID, @"content":content};
    [[XBRequest sharedInstance] postDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        [EasyShowLodingView hidenLoding];
        NSLog(@"发布回复 ---- %@",responseResult);
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                [self getData];
            }else{
                [[UIApplication sharedApplication].keyWindow makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
                
            }
        }
    }];
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kWindowW, kWindowH - Height_NavBar - self.bottomView.frame.size.height) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = BackGroundColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [self getData];
        }];
        
        [_tableView registerNib:[UINib nibWithNibName:@"CYCommentReplyListTableViewCell" bundle:nil] forCellReuseIdentifier:@"CYCommentReplyListTableViewCell"];
    }
    return _tableView;
}

- (NSMutableArray *)dataSourceArr{
    if (!_dataSourceArr) {
        _dataSourceArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataSourceArr;
}

- (UIView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[UIView alloc] init];
        _bottomView.backgroundColor = [UIColor whiteColor];
        if (HX_IS_IPhoneX_All) {
            _bottomView.frame = CGRectMake(0, kWindowH - 83 - Height_NavBar, kWindowW, 83);
        }else{
            _bottomView.frame = CGRectMake(0, kWindowH - 48 - Height_NavBar, kWindowW, 48);
        }
        
        UIView *contrainerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWindowW, 48)];
        [_bottomView addSubview:contrainerView];
        
        UIButton *commentBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [commentBtn setFrame:CGRectMake(15, 9, kWindowW - 65, 30)];
        commentBtn.layer.cornerRadius = 15;
        commentBtn.layer.borderWidth = 1;
        commentBtn.layer.borderColor = RGBOF(0xe3e3e3).CGColor;
        commentBtn.layer.masksToBounds = YES;
        [commentBtn setBackgroundColor:RGBOF(0xf7f7f7)];
        [commentBtn setTitle:@"   请赐评" forState:UIControlStateNormal];
        [commentBtn setImage:[UIImage imageNamed:@"wd_wdwd"] forState:UIControlStateNormal];
        [commentBtn setTitleColor:RGBOF(0x999999) forState:UIControlStateNormal];
        commentBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        commentBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [commentBtn setContentEdgeInsets:UIEdgeInsetsMake(0, 25, 0, 0)];
        [commentBtn addTarget:self action:@selector(commentAction) forControlEvents:UIControlEventTouchUpInside];
        [contrainerView addSubview:commentBtn];
        
        CGFloat width = 20;
        CGFloat height = 20;
        UIButton *commentBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
        [commentBtn1 setFrame:CGRectMake(kWindowW - 15 - 20 , 12, width, height)];
        [commentBtn1 setImage:[UIImage imageNamed:@"ksp_zan"] forState:UIControlStateNormal];
        [commentBtn1 addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [commentBtn1 setImage:[UIImage imageNamed:@"zan_sel"] forState:UIControlStateSelected];
        [contrainerView addSubview:commentBtn1];
        _zanBtn = commentBtn1;
        
    }
    return _bottomView;
}

- (void)initZanData{
    if ([self.commentModel.isLike integerValue] == 1) {
        _zanBtn.selected = YES;
    }else{
        _zanBtn.selected = NO;
    }
}

- (void)btnClick:(UIButton *)sender{
    if ([self.commentModel.isLike integerValue] == 1) {
        [self cancleZanWithCommentModel:self.commentModel];
    }else{
        [self zanWithCommentModel:self.commentModel];
    }
}

#pragma mark - 给评论赞和取消点赞
- (void)cancleZanWithCommentModel:(CYCommentModel *)commentModel{
    if (![YLUserInfo isLogIn]) {
        LoginViewController *login = [[LoginViewController alloc] init];
        [[AppDelegate sharedAppDelegate] pushViewController:login];
        return;
    }
    [EasyShowLodingView showLoding];
    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"cancleLike"];
    NSDictionary *param = @{@"type":@2, @"articleId":commentModel.ID, @"origin":self.commentModel.type, @"toLikerId":commentModel.userId};
    [[XBRequest sharedInstance] postDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        [EasyShowLodingView hidenLoding];
        NSLog(@"取消点赞 ---- %@",responseResult);
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                commentModel.isLike = [NSNumber numberWithInteger:2];
                NSInteger tag = [commentModel.likeNumber integerValue];
                commentModel.likeNumber = [NSString stringWithFormat:@"%ld",(tag - 1)];
                [self initZanData];
            }else{
                [[UIApplication sharedApplication].keyWindow makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
                
            }
        }
    }];
}

- (void)zanWithCommentModel:(CYCommentModel *)commentModel{
    if (![YLUserInfo isLogIn]) {
        LoginViewController *login = [[LoginViewController alloc] init];
        [[AppDelegate sharedAppDelegate] pushViewController:login];
        return;
    }
    [EasyShowLodingView showLoding];
    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"addLike"];
    NSDictionary *param = @{@"type":@2, @"likeId":commentModel.ID, @"origin":self.commentModel.type, @"toLikerId":commentModel.userId};
    [[XBRequest sharedInstance] postDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        [EasyShowLodingView hidenLoding];
        NSLog(@"赞评论 ---- %@",responseResult);
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                commentModel.isLike = [NSNumber numberWithInteger:1];
                NSInteger tag = [commentModel.likeNumber integerValue];
                commentModel.likeNumber = [NSString stringWithFormat:@"%ld",(tag + 1)];
                [self initZanData];
            }else{
                [[UIApplication sharedApplication].keyWindow makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
}

#pragma mark - 评论
- (void)commentAction{
    [self.growingTextView becomeFirstResponder];
}

- (UIView *)inputView{
    if (!_inputView) {
        _inputView = [[UIView alloc] init];
        _inputView.backgroundColor = [UIColor whiteColor];
        HPGrowingTextView *group = [[HPGrowingTextView alloc] init];
        self.growingTextView = group;
        group.delegate = self;
        group.font = [UIFont systemFontOfSize:14];
        group.minNumberOfLines = 1;
        group.maxNumberOfLines = 5;
        group.placeholder = @"请赐评";
        group.returnKeyType = UIReturnKeySend;
        group.enablesReturnKeyAutomatically = YES;
        group.backgroundColor = RGBOF(0xf6f6f6);
        group.layer.cornerRadius = 5;
        [_inputView addSubview:group];
        [group mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self->_inputView).with.mas_offset(10);
            make.top.equalTo(self->_inputView).with.mas_offset(5);
            make.right.equalTo(self->_inputView).with.mas_offset(-10);
            make.bottom.equalTo(self->_inputView).with.mas_offset(-5);
            
        }];
    }
    return _inputView;
}

#pragma mark - UIKeyboardNotification

- (void)keyboardWillShow:(NSNotification *)notification
{
    CGRect endRect = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    NSLog(@"keyboardWillShow -- %f",endRect.size.height);
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        [self.inputView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view).with.mas_equalTo(-endRect.size.height);
            make.left.equalTo(self.view).with.mas_offset(0);
            make.right.equalTo(self.view).with.mas_offset(0);
            make.height.mas_equalTo(50);
        }];
        [self.view layoutIfNeeded];
    } completion:nil];
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        [self.inputView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view).with.mas_equalTo(self->_inputViewHeight);
        }];
        [self.view layoutIfNeeded];
    } completion:nil];
}

#pragma mark - UITextViewDelegate

- (void)growingTextView:(HPGrowingTextView *)growingTextView willChangeHeight:(float)height
{
    _inputViewHeight = height + 14;
    [self.inputView mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.height.mas_equalTo(height + 14);
    }];
    [self.view layoutIfNeeded];
}

- (BOOL)growingTextViewShouldReturn:(HPGrowingTextView *)growingTextView
{
    [self.growingTextView resignFirstResponder];
    return YES;
}

- (BOOL)growingTextView:(HPGrowingTextView *)growingTextView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    //判断是回车键就发送出去
    if ([text isEqualToString:@"\n"])
    {
        [self fasongHuiFuWithText:self.growingTextView.text];

        self.growingTextView.text = @"";
        [self.growingTextView resignFirstResponder];
        [self.tableView reloadData];
        return NO;
    }
    return YES;
}

- (void)growingTextViewDidChange:(HPGrowingTextView *)growingTextView
{
    UITextRange *selectedRange = growingTextView.internalTextView.markedTextRange;
    NSString *newText = [growingTextView.internalTextView textInRange:selectedRange];
    
    if (newText.length < 1)
    {
        // 高亮输入框中的@
        UITextView *textView = self.growingTextView.internalTextView;
        NSRange range = textView.selectedRange;
        
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:textView.text];
        [string addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, string.string.length)];
        
        
        textView.attributedText = string;
        textView.selectedRange = range;
    }
}

- (void)growingTextViewDidChangeSelection:(HPGrowingTextView *)growingTextView
{
    // 光标不能点落在@词中间
    NSRange range = growingTextView.selectedRange;
    if (range.length > 0)
    {
        // 选择文本时可以
        return;
    }
    
}

@end
